/*
 * SessionAdminTipoDestinoBean.java
 *
 * Created on January 8, 2008, 9:09 AM
 * Copyright FSanchez
 */
package gestionportletadmintipodestino;


import com.computec.admintipodestinocliente.dto.TipoDestinoClienteDto;
import com.src.computec.radar.base.ldap.dto.LdapUserDto;
import com.src.computec.radar.base.source.CoreSource;
import com.src.computec.radar.services.utilities.consultas.delegate.ConsultasDelegate;
import com.src.computec.radar.services.utilities.consultas.exception.ConsultasException;
import com.src.computec.radar.services.utilities.dto.ClienteDto;
import com.src.computec.radar.services.utilities.dto.DepartamentoDto;
import com.src.computec.radar.services.utilities.dto.MunicipioDto;
import com.sun.rave.web.ui.appbase.AbstractSessionBean;
import com.sun.rave.web.ui.model.Option;
import java.util.Iterator;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;

/**
 * <p>Session scope data bean for your application.  Create properties
 *  here to represent cached data that should be made available across
 *  multiple HTTP requests for an individual user.</p>
 *
 * <p>An instance of this class will be created for you automatically,
 * the first time your application evaluates a value binding expression
 * or method binding expression that references a managed bean using
 * this class.</p>
 */
public class SessionAdminTipoDestinoBean extends AbstractSessionBean {
    // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Definition">
    private int __placeholder;
    
    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    // </editor-fold>
    
    
     //<editor-fold defaultstate="collapsed" desc="Parametros Aplicacion">
    private Option[] optionClientes;
    private Option[] optionTipoDestinoCliente;
    private Option[] optionDepartamentos;
    private Option[] optionMunicipio;
    private LdapUserDto ldapUserDto = null;
    private String ldapUser = new String();
    private List matrizTDC;
    private boolean renderTable=false;
    private boolean renderAlert=false;
    private boolean renderGerencia=false;
    // </editor-fold>
    
   

    /** 
     * <p>Construct a new session data bean instance.</p>
     */
    public SessionAdminTipoDestinoBean() {
	  try {
	   //this.setLdapUser("nrivera.computec");
          this.ldapUser = this.getUIdByDomainName(FacesPortletUtil.getPortletRequest(FacesContext.getCurrentInstance()).getRemoteUser());
          
            this.findRolesUser();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 
     * <p>Return a reference to the scoped data bean.</p>
     */
    protected ApplicationAdminTipoDestinoBean getApplicationAdminTipoDestinoBean() {
        return (ApplicationAdminTipoDestinoBean)getBean("ApplicationAdminTipoDestinoBean");
    }


    /** 
     * <p>This method is called when this bean is initially added to
     * session scope.  Typically, this occurs as a result of evaluating
     * a value binding or method binding expression, which utilizes the
     * managed bean facility to instantiate this bean and store it into
     * session scope.</p>
     * 
     * <p>You may customize this method to initialize and cache data values
     * or resources that are required for the lifetime of a particular
     * user session.</p>
     */
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
	ConsultasDelegate consultasDelegate=new ConsultasDelegate();
	
	
	try{
	 this.setOptionClientes(this.fillOptionClientes(consultasDelegate.getClientes()));
	 this.setOptionTipoDestinoCliente(this.fillOptionTipoDestinoCliente(null));
	 this.setOptionDepartamentos(this.fillOptionDepartamentos(consultasDelegate.getDepartamentos()));
	 this.setOptionMunicipio(this.fillOptionMunicipio(null));
	}catch(ConsultasException cex){
	    cex.printStackTrace();
	}
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("SessionBean1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here

    }

    /** 
     * <p>This method is called when the session containing it is about to be
     * passivated.  Typically, this occurs in a distributed servlet container
     * when the session is about to be transferred to a different
     * container instance, after which the <code>activate()</code> method
     * will be called to indicate that the transfer is complete.</p>
     * 
     * <p>You may customize this method to release references to session data
     * or resources that can not be serialized with the session itself.</p>
     */
    public void passivate() {
    }

    /** 
     * <p>This method is called when the session containing it was
     * reactivated.</p>
     * 
     * <p>You may customize this method to reacquire references to session
     * data or resources that could not be serialized with the
     * session itself.</p>
     */
    public void activate() {
    }

    /** 
     * <p>This method is called when this bean is removed from
     * session scope.  Typically, this occurs as a result of
     * the session timing out or being terminated by the application.</p>
     * 
     * <p>You may customize this method to clean up resources allocated
     * during the execution of the <code>init()</code> method, or
     * at any later time during the lifetime of the application.</p>
     */
    public void destroy() {
    }
    
    public void findRolesUser() throws ConsultasException {
        ConsultasDelegate consultasDelegate = new ConsultasDelegate();
        LdapUserDto ldapUserDtoAux = new LdapUserDto();
        ldapUserDtoAux.setIdLdap(this.getLdapUser());
        ldapUserDtoAux = consultasDelegate.getLdapUserByPrimaryKey(ldapUserDtoAux);
        this.setLdapUserDto(ldapUserDtoAux);
        Iterator iterRoles = ldapUserDtoAux.getRoles().iterator();	
        while(iterRoles.hasNext()) {
            String nombreRole = (String) iterRoles.next();
         if ((nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_gerencia_cn")) == 0)  || (nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_administrador_cn"))==0)) {                
		this.renderGerencia=true;
            }
        }	
    }
     
    public Option[] fillOptionClientes(List listClientes) {
        int indice = 1;
        Option[] optionClientesAux;
        if (listClientes!=null && listClientes.size()>0) {
            optionClientesAux = new Option[listClientes.size() + 1];
            optionClientesAux[0] = new Option("", "Seleccione...");
            Iterator iterator = listClientes.iterator();
	    while (iterator.hasNext()) {
		ClienteDto clienteDtoAux = (ClienteDto)iterator.next();
		optionClientesAux[indice++] = new Option(clienteDtoAux.getCodigoCliente(), clienteDtoAux.getRazonSocial());
	    }            
        }
        else {
            optionClientesAux = new Option[1];
            optionClientesAux[0] = new Option("", "Seleccione...");
        }
       
        return optionClientesAux;
    }
    
    
     public Option[] fillOptionTipoDestinoCliente(List listTDClientes) {
        int indice = 1;
        Option[] optionClientesAux;
        if (listTDClientes!=null && listTDClientes.size()>0) {
            optionClientesAux = new Option[listTDClientes.size() + 1];
            optionClientesAux[0] = new Option("", "Seleccione...");
            Iterator iterator = listTDClientes.iterator();
	    while (iterator.hasNext()) {
		TipoDestinoClienteDto tipoDestinoClienteDto = (TipoDestinoClienteDto)iterator.next();
		optionClientesAux[indice++] = new Option(tipoDestinoClienteDto.getCodigoTipoDestinoCliente(), tipoDestinoClienteDto.getNombreTipoDestinoCliente());
	    }            
        }
        else {
            optionClientesAux = new Option[1];
            optionClientesAux[0] = new Option("", "Seleccione...");
        }
       
        return optionClientesAux;
    }
     
     
    public Option[] fillOptionDepartamentos(List listDepartamentos) {
        int indice = 1;
        Option[] optionDepartamentoAux;
        if (listDepartamentos!=null && listDepartamentos.size()>0) {
            optionDepartamentoAux = new Option[listDepartamentos.size() + 1];
            optionDepartamentoAux[0] = new Option("", "Seleccione...");
            Iterator iterator = listDepartamentos.iterator();
	    while (iterator.hasNext()) {
		DepartamentoDto depDto = (DepartamentoDto)iterator.next();
		optionDepartamentoAux[indice++] = new Option(depDto.getCodigoDepartamento(), depDto.getNombreDepartamento());
	    }            
        }
        else {
            optionDepartamentoAux = new Option[1];
            optionDepartamentoAux[0] = new Option("", "Seleccione...");
        }       
        return optionDepartamentoAux;
    }
    
    public Option[] fillOptionMunicipio(List listMunicipios) {
        int indice = 1;
        Option[] optionMunicipioAux;
        if (listMunicipios!=null && listMunicipios.size()>0) {
            optionMunicipioAux = new Option[listMunicipios.size() + 1];
            optionMunicipioAux[0] = new Option("", "Seleccione...");
            Iterator iterator = listMunicipios.iterator();
	    while (iterator.hasNext()) {
		MunicipioDto munDto = (MunicipioDto)iterator.next();
		optionMunicipioAux[indice++] = new Option(munDto.getCodigoMunicipio(), munDto.getNombreMunicipio());
	    }            
        }
        else {
            optionMunicipioAux = new Option[1];
            optionMunicipioAux[0] = new Option("", "Seleccione...");
        }       
        return optionMunicipioAux;
    }
     
    public Option[] getOptionClientes() {
        return optionClientes;
    }

    public void setOptionClientes(Option[] optionClientes) {
        this.optionClientes = optionClientes;
    }

    public LdapUserDto getLdapUserDto() {
        return ldapUserDto;
    }

    public void setLdapUserDto(LdapUserDto ldapUserDto) {
        this.ldapUserDto = ldapUserDto;
    }

    public String getLdapUser() {
        return ldapUser;
    }

    public void setLdapUser(String ldapUser) {
        this.ldapUser = ldapUser;
    }

    public Option[] getOptionTipoDestinoCliente() {
        return optionTipoDestinoCliente;
    }

    public void setOptionTipoDestinoCliente(Option[] optionTipoDestinoCliente) {
        this.optionTipoDestinoCliente = optionTipoDestinoCliente;
    }

    public Option[] getOptionDepartamentos() {
        return optionDepartamentos;
    }

    public void setOptionDepartamentos(Option[] optionDepartamentos) {
        this.optionDepartamentos = optionDepartamentos;
    }

    public Option[] getOptionMunicipio() {
        return optionMunicipio;
    }

    public void setOptionMunicipio(Option[] optionMunicipio) {
        this.optionMunicipio = optionMunicipio;
    }

    public List getMatrizTDC() {
        return matrizTDC;
    }

    public void setMatrizTDC(List matrizTDC) {
        this.matrizTDC = matrizTDC;
    }

    public boolean isRenderTable() {
        return renderTable;
    }

    public void setRenderTable(boolean renderTable) {
        this.renderTable = renderTable;
    }

    public boolean isRenderAlert() {
        return renderAlert;
    }

    public void setRenderAlert(boolean renderAlert) {
        this.renderAlert = renderAlert;
    }
    
     private String getUIdByDomainName(String domainName)
    {
        String[] tokens =  domainName.split(",");
        
        if(tokens.length > 0)
        {
            String[] uIdTokens = (tokens[0]).split("=");
            
            if(uIdTokens.length == 2)
            {
                return uIdTokens[1];
            }            
        }
        return "";
    }  

    public boolean isRenderGerencia() {
        return renderGerencia;
    }

    public void setRenderGerencia(boolean renderGerencia) {
        this.renderGerencia = renderGerencia;
    }
}
